package org.example.blogserver.dao.impl;

import org.example.blogserver.dao.CommentDao;
import org.example.blogserver.entity.Article;
import org.example.blogserver.entity.Comment;
import org.example.blogserver.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CommentDaoImpl implements CommentDao {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public CommentDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int addComment(Comment comment) {
        String sql = "INSERT INTO ms_comment (content, article_id, author_account, parent_id, level) " +
                "VALUES (?, ?, ?, ?, ?);UPDATE ms_article SET comment_counts = comment_counts + 1 WHERE id = ?";

        return jdbcTemplate.update(sql, comment.getContent(), comment.getArticleId(),
                comment.getAuthorAccount(), comment.getParentId(), comment.getLevel(),comment.getArticleId());
    }

    @Override
    public int deleteCommentById(Long id) {
        String sql = "DELETE FROM ms_comment WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public Comment findCommentById(Long id) {
        String sql = "SELECT * FROM ms_comment WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Comment.class));
    }
    @Override
    public List<Comment> findCommentsByArticleId(Long articleId) {
        String sql = "SELECT * FROM ms_comment WHERE article_id = ?";
        return jdbcTemplate.query(sql, new Object[]{articleId}, new BeanPropertyRowMapper<>(Comment.class));
    }
    @Override
    public List<Comment> findCommentsByParentId(Long articleId) {
        String sql = "SELECT * FROM ms_comment WHERE ms_comment.parent_id = ?";
        return jdbcTemplate.query(sql, new Object[]{articleId}, new BeanPropertyRowMapper<>(Comment.class));
    }
}
